﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Web;

namespace MusicPlow
{
    public class GrooveShark
    {
        const string c_requestFormat = "http://tinysong.com/s/{0}?format=json&key={1}&limit={2}";
        const string c_tinySongApiKey = "7dfc78eed0a5995b50fa6e61ba8a51ca";
        
        public static Task<TimedOperation<List<GrooveSharkResult>>> GetResults(string text, int amount)
        {
            DateTime startTime = DateTime.Now;
            return WebRequestExtensions.ExecuteJsonWebRequestTask<TimedOperation<List<GrooveSharkResult>>>(
                string.Format(c_requestFormat, HttpUtility.UrlEncode(text), c_tinySongApiKey, amount),
                gsresult => 
                    {
                        TimeSpan runTime = DateTime.Now - startTime;
                        var results = new List<GrooveSharkResult>();
                        
                        foreach (var itemResult in gsresult)
                        {
                            results.Add(new GrooveSharkResult
                            {
                                SongId = itemResult["SongID"],
                                SongName = itemResult["SongName"],
                                AlbumName = itemResult["AlbumName"],
                                ArtistName = itemResult["ArtistName"]
                            });
                        }
                        return new TimedOperation<List<GrooveSharkResult>>(results, runTime);
                    });
        }
    }

    public class GrooveSharkResult
    {
        public int SongId;
        public string SongName;
        public string AlbumName;
        public string ArtistName;

        public string ImageSearchString
        {
            get
            {
                if (!string.IsNullOrWhiteSpace(AlbumName))
                {
                    return string.Format("{0} {1}", ArtistName, AlbumName);
                }
                else
                {
                    return string.Format("{0} {1}", ArtistName, SongName);
                }
            }
        }
    }
}
